package com.netforce.util.convert;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import com.google.gson.Gson;

public class FromJsonConverter<Type> implements Converter<String, Type>
{
  public FromJsonConverter(Class<Type> aClass)
  {
    type = aClass;
  }

  @Override
  public Type convert(String aSource) throws ConverterException
  {
    try
    {
      String source = new String(aSource.getBytes(), "UTF-8");

      Gson gson = new Gson();
      return gson.fromJson(new StringReader(source), type);
    }
    catch (UnsupportedEncodingException anException)
    {
      throw new ConverterException("Unable to convert from json source " + aSource, anException);
    }
  }

  protected Class<Type> type;
}
